package com.auto.learning.activity;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.adapter.ImagePublishAdapter;
import com.auto.learning.bean.ImageCommentBean;
import com.auto.learning.bean.ImageItem;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.UploadedImageBean;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FileUtil;
import com.auto.learning.tools.ImageDisplayer;
import com.auto.learning.tools.IntentConstants;
import com.auto.learning.view.MyProgressDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.otto.Subscribe;

public class PublicCommentActivity extends Activity {

	private TextView tv_action_left, tv_action_right;
	private EditText et_message;
	private GridView gv_image;
	private ImagePublishAdapter adapter;
	private ArrayList<ImageItem> data = new ArrayList<ImageItem>();
	private final static int UPLOAD_IMAGE_SUCCESS = 1;
	private final static int UPLOAD_IMAGE_FAIL = 2;
	private final static int SUBMIT_SUCCESS = 3;
	private int bookId ;
	private MyProgressDialog myProgressDialog;
	
	
	private Handle handler = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UPLOAD_IMAGE_SUCCESS:
				
				break;
			case UPLOAD_IMAGE_FAIL:
				if (myProgressDialog != null) {
					myProgressDialog.dismiss();
				}
				CommonMethod.makeNotice(PublicCommentActivity.this, msg.obj.toString());
				break;
			case SUBMIT_SUCCESS:
				if (myProgressDialog != null) {
					myProgressDialog.dismiss();
				}
				CommonMethod.makeNotice(PublicCommentActivity.this, "发表书评成功！太棒了！");
				ResponeResult responeResult =(ResponeResult) msg.obj;
				ImageCommentBean result = new Gson().fromJson(responeResult.getData(), new TypeToken<ImageCommentBean>() {}.getType());
				if (result != null) {
					EventBus.getEventBus("refresh_comment_list").post(result);
					finish();
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.public_comment_activity);
		bookId = getIntent().getIntExtra("bookId", 0);
		initData();
		initView();
		registerEvent();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		initData();
		initView();
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}

	public void initView() {
		myProgressDialog = MyProgressDialog.createLoadingDialog(this);
		tv_action_left = (TextView) findViewById(R.id.tv_action_left);
		tv_action_right = (TextView) findViewById(R.id.tv_action_right);
		et_message = (EditText) findViewById(R.id.et_message);
		gv_image = (GridView) findViewById(R.id.gv_image);
		gv_image.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new ImagePublishAdapter(this, data);
		gv_image.setAdapter(adapter);
		gv_image.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == getDataSize()){
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
					imm.hideSoftInputFromWindow(et_message.getWindowToken(), 0);
					new PopupWindows(PublicCommentActivity.this, gv_image);
				}else{
					Intent intent = new Intent(PublicCommentActivity.this,ImageZoomActivity.class);
					intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST, (Serializable) data);
					intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, position);
					startActivity(intent);
				}
			}
		});
		tv_action_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		tv_action_right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String msg = et_message.getText().toString();
				if (TextUtils.isEmpty(msg.trim())) {
					CommonMethod.makeNotice(PublicCommentActivity.this, "评论内容不能为空！");
					et_message.requestFocus();
					return;
				}else {
					myProgressDialog.setCanceledOnTouchOutside(false);
					myProgressDialog.show();
					uploadImage(msg);
				}
			}
		});
	}
	
	
	
	
	/**
	 * 上传图片
	 */
	public void uploadImage(final String comment){
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				StringBuilder imageUrls = new StringBuilder();
				if (data != null && data.size() > 0) {
					for (ImageItem item : data) {
						try {
							String imageUrl = "";
							List<UploadedImageBean> list = StaticReference.mutilDBSupport.getDao(UploadedImageBean.class).queryBuilder().where().eq("localPath", item.sourcePath).query();
							if (list != null && list.size() > 0) {
								imageUrl = list.get(0).getNetImagePath();
							} else {
								String tempFilePath = FileUtil.saveBitmap(CommonMethod.getFileName(item.sourcePath), ImageDisplayer.getInstance(PublicCommentActivity.this).getimage(item.sourcePath));
								imageUrl = CommonMethod.uploadImageFile(PublicCommentActivity.this, handler, TextUtils.isEmpty(tempFilePath) ? item.sourcePath : tempFilePath, UPLOAD_IMAGE_SUCCESS, UPLOAD_IMAGE_FAIL);
								if (!TextUtils.isEmpty(tempFilePath)) {
									File tempFile = new File(tempFilePath);
									if (tempFile != null && tempFile.exists()) {
										tempFile.delete();
									}
								}
								if (TextUtils.isEmpty(imageUrl)) break;
								else {
									UploadedImageBean imageBean = new UploadedImageBean();
									imageBean.setLocalPath(item.sourcePath);
									imageBean.setNetImagePath(imageUrl);
									Log.d("imageUrl", imageUrl);
									StaticReference.mutilDBSupport.getDao(UploadedImageBean.class).create(imageBean);
								}
							}
							if (TextUtils.isEmpty(imageUrls)) {
								imageUrls.append(imageUrl);
							} else {
								imageUrls.append(","+imageUrl);
							}
							if (data.indexOf(item) == (data.size() - 1)) {
								submitComment(bookId, comment, imageUrls.toString());
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else {
					submitComment(bookId, comment, "");
				}
			}
		});
	}
	
	@Subscribe
	public void onDelItemEvent(ImageItem imageItem){
		if (data != null) {
			for (int i = 0; i < data.size(); i++) {
				if (imageItem.sourcePath.equals(data.get(i).sourcePath)) {
					data.remove(i);
					break;
				}
			}
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		unRegisterEvent();
		super.onDestroy();
	}
	
	private void registerEvent(){
		EventBus.getEventBus("del_choosed_image").register(this);
	}
	
	private void unRegisterEvent(){
		EventBus.getEventBus("del_choosed_image").unregister(this);
	}
	
	
	private int getDataSize(){
		return data == null ? 0 : data.size();
	}
	
	public class PopupWindows extends PopupWindow{
		public PopupWindows(Context mContext, View parent){
			View view = View.inflate(mContext, R.layout.item_popupwindow, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,R.anim.push_bottom_in_2));
			setWidth(LayoutParams.MATCH_PARENT);
			setHeight(LayoutParams.MATCH_PARENT);
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();
			Button bt1 = (Button) view.findViewById(R.id.ac_cuh_camerabtn);
			Button bt2 = (Button) view.findViewById(R.id.ac_cuh_localbtn);
			Button bt3 = (Button) view.findViewById(R.id.ac_cuh_cancelbtn);
			bt1.setOnClickListener(new OnClickListener(){
				
				public void onClick(View v){
					takePhoto();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener(){
				
				public void onClick(View v){
					ArrayList<String> tempList = new ArrayList<String>();
					if (data != null) {
						for (ImageItem item : data) {
							tempList.add(item.sourcePath);
						}
					}
					Intent intent = new Intent(PublicCommentActivity.this, ImageChooseActivity.class);
					intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, getAvailableSize());
					intent.putStringArrayListExtra(IntentConstants.EXTRA_HAS_CHOOSEED_IMG, tempList);
					startActivity(intent);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener(){
				
				public void onClick(View v){
					dismiss();
				}
			});
		}
	}
	
	@SuppressWarnings("unchecked")
	private void initData(){
		List<ImageItem> incomingDataList = (List<ImageItem>) getIntent().getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
		if (incomingDataList != null){
			data.addAll(incomingDataList);
		}
	}
	
	
	private int getAvailableSize(){
		int availSize = HttpRequestHelper.MAX_IMAGE_SIZE - data.size();
		if (availSize >= 0){
			return availSize;
		}
		return 0;
	}
	
	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";
	
	public void takePhoto(){
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
		if (!vFile.exists()){
			File vDirPath = vFile.getParentFile();
			vDirPath.mkdirs();
		}else{
			if (vFile.exists()){
				vFile.delete();
			}
		}
		path = vFile.getPath();
		Uri cameraUri = Uri.fromFile(vFile);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode){
		case TAKE_PICTURE:
			if (this.data.size() < HttpRequestHelper.MAX_IMAGE_SIZE && resultCode == -1 && !TextUtils.isEmpty(path)){
				ImageItem item = new ImageItem();
				item.sourcePath = path;
				this.data.add(item);
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
			}
			break;
		}
	}
	
	/**
	 * 提交评论
	 */
	private void submitComment(int bookId, String content,String imageUrls){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(bookId)));
		params.add(new BasicNameValuePair("comment", content));
		params.add(new BasicNameValuePair("imgUrl", imageUrls));
		HttpRequestHelper.executeHttpDataUnThread(this, HttpRequestHelper.COMMENT_SUBMIT, params, handler, SUBMIT_SUCCESS,UPLOAD_IMAGE_FAIL);
	}
}
